<?php

class AttendanceController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('create','update','delete','index','view', 'OutputExcel', 'list'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
    
    public function getDays()
    {
        $year = date('Y');
        $month = date('n');
        $day = date('j');
        //通过mktime()函数和date()函数获得当月的总天数。
        $daysInMonth = date("t",mktime(0,0,0,$month,1,$year));
        return $daysInMonth;
    }
    
    public function actionOutputExcel()
    {
        if(empty($_GET['year']))
        {
            throw new Exception('year is missing.');
            return false;
        }
        
        if(empty($_GET['month']))
        {
            throw new Exception('month is missing.');
            return false;
        }
        
        $year = $_GET['year'];
        $month = $_GET['month'];
        
        $persons = array();
        
        //make sure php have enough time to create excel
        ini_set('max_execution_time', 600);
        
        Yii::import('common.extensions.phpexcel.XPHPExcel');
        $objPHPExcel = XPHPExcel::createPHPExcel();
//        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
//                                     ->setLastModifiedBy("Maarten Balliauw")
//                                     ->setTitle("Office 2007 XLSX Test Document")
//                                     ->setSubject("Office 2007 XLSX Test Document")
//                                     ->setDescription("Document for Office 2007 XLSX, generated using PHP classes.")
//                                     ->setKeywords("office 2007 openxml php")
//                                     ->setCategory("Test result file");
//
//        $objPHPExcel->setActiveSheetIndex(0);
//        $objRichText = new PHPExcel_RichText();
//        $objRichText->createText('');
//        $objPayable = $objRichText->createTextRun('PHP导出的Excel');
//        $objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_RED ));
//        $objPayable->getFont()->setBold(true);
//        $objPayable->getFont()->setSize(24);
//        $objPHPExcel->getActiveSheet()->getCell('B1')->setValue($objRichText);
//        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);		// 加粗
//        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(24);			// 字体大小
//        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);	// 文本颜色
//        $objPHPExcel->getActiveSheet()->getStyle('A1:G1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
//        $objPHPExcel->getActiveSheet()->getStyle('A1:G1')->getFill()->getStartColor()->setARGB('00FFFFE3');			// 底纹

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle('报假表');
        
        // 列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);

        $days = CommonHelper::getDaysByDate($year, $month);
        $str = $year.'-'.$month.'-';
        $criteria = new EMongoCriteria;
        $criteria->setSelect(array('_id'));
        
        $users = User::model()->findAll($criteria);
        
        if(is_array($users) && ! empty($users))
        {
            foreach($users as $u)
            {
                if( ! ($u instanceof User))
                    continue;
                
                $attendances = Attendance::model()->getAllByUserMonth($u->getId(), $year, $month, false);
                if(is_array($attendances) && ! empty($attendances))
                    $persons[] = $attendances;
            }
        }
        
        if( ! empty($persons))
        {
            $j = 0;
            foreach($persons as $k=>$p)
            {
                for($i=1; $i<=$days; $i++)
                {
                    $j++;
                    $objPHPExcel->getActiveSheet()->setCellValue('A'.$j, $str.$i);
                    foreach($p as $att)
                    {
                        if( ! ($att instanceof Attendance)
                        || (strtotime($str.$i) < $att->start_time 
                        || strtotime($str.$i) > $att->end_time))
                            continue;

                        $objPHPExcel->getActiveSheet()->setCellValue('B'.$j, $att->getUser()->number);
                        $objPHPExcel->getActiveSheet()->setCellValue('C'.$j, $att->getUser()->getDisplayName());
                        $objPHPExcel->getActiveSheet()->setCellValue('D'.$j, $att->getItemType()->getName());
                        $objPHPExcel->getActiveSheet()->setCellValue('E'.$j, $att->getDisplayStatus());
                        $objPHPExcel->getActiveSheet()->setCellValue('F'.$j, date('Y-m-d', $att->start_time));
                        $objPHPExcel->getActiveSheet()->setCellValue('G'.$j, date('Y-m-d', $att->end_time));
                        $oldValue = $objPHPExcel->getActiveSheet()->getCell('H'.$j);

                        if( ! empty($oldValue))
                            $objPHPExcel->getActiveSheet()->setCellValue('H'.$j, $oldValue.' '.$att->about);
                        else
                            $objPHPExcel->getActiveSheet()->setCellValue('H'.$j, $att->about);
                    }
                }
            }
        }
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="Holiday_'.$year.'_'.$month.'.xlsx"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        
        return true;
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Attendance;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Attendance']))
		{
			$model->attributes=$_POST['Attendance'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Attendance']))
		{
			$model->attributes=$_POST['Attendance'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
//	public function actionIndex()
//	{
//		$dataProvider=new EMongoDocumentDataProvider('Attendance');
//		$this->render('index',array(
//			'dataProvider'=>$dataProvider,
//		));
//	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model = new Attendance('search');
        $model->unsetAttributes();  // clear any default values
        $model->setDbCriteria(array(
            'sort'=>array('ctime'=>EMongoCriteria::SORT_DESC),
            'user_id'=> User::model()->getUserId(),
        ));
        
        $conditions = array(
            'user_id'=> User::model()->getUserId(),
        );
        $criteria = new EMongoCriteria;
        $criteria->setConditions($conditions);
        $criteria->setSort(array('ctime'=>EMongoCriteria::SORT_DESC));
        
        if(isset($_GET['Attendance']))
        {
            foreach($_GET['Attendance'] as $k => $v)
            {
                $v = trim($v);
                if('start_time' === $k)
                    $v = (int)strtotime($v);
                
                if( ! empty($v))
                    $conditions[$k] = array('$regex'=>'.*' . $v . '.*', '$options'=>'i');
            }    
            if( ! empty($conditions))
                $criteria->setConditions($conditions);
            
            $dataProvider = new EMongoDocumentDataProvider('Attendance', array('criteria'=>$criteria));
        }
        else
            $dataProvider = new EMongoDocumentDataProvider('Attendance', array('criteria'=>$criteria));

		$this->render('index', array(
			'model'=>$model,
            'dataProvider'=>$dataProvider,
		));
	}
    
    public function actionList($id)
    {
        $user = User::model()->getUser($id);
        if( empty($user))
            throw new Exception(400,'Invalid request. Please do not repeat this request again.');
            
        $model = new Attendance('search');
        $model->unsetAttributes();  // clear any default values
        $model->setDbCriteria(array(
            'sort'=>array('ctime'=>EMongoCriteria::SORT_DESC),
            'user_id'=> $id
        ));

        if(isset($_GET['Attendance']))
        {
            $conditions = array();
            foreach($_GET['Attendance'] as $k => $v)
            {
                $v = trim($v);
                if('apply_time' === $k)
                    $v = (int)strtotime($v);
                
                if( ! empty($v))
                    $conditions[$k] = array('$regex'=>'.*' . $v . '.*', '$options'=>'i');
            }    

            $criteria = new EMongoCriteria;
            if( ! empty($conditions))
                $criteria->setConditions($conditions);
            
            $dataProvider = new EMongoDocumentDataProvider('Attendance', array('criteria'=>$criteria));
        }
        else
            $dataProvider = new EMongoDocumentDataProvider($model);

		$this->render('index', array(
			'model'=>$model,
            'dataProvider'=>$dataProvider,
		));
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model = Attendance::model()->findByPk(new MongoId($id));
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='attendance-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
